import { 
  Color,
  DoubleSide,
  Group,
  LineBasicMaterial,
  LineSegments,
  Mesh,
  MeshBasicMaterial,
  PerspectiveCamera, PlaneBufferGeometry, 
  Scene, WebGLRenderer 
} from 'three'
import stats from '../../utils/stats'
import dat from 'dat.gui'

const scene = new Scene()
const camera = new PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000)
camera.position.set(0, 0, 100)
camera.lookAt(0, 0, 0)

let group = new Group()
let planeGeometry = new PlaneBufferGeometry(20, 20, 1, 1)
const planeMaterial = new MeshBasicMaterial({
  color: 0xff9900, 
  side: DoubleSide
})
const lineMaterial = new LineBasicMaterial({
  color: 0xffffff,
  transparent: true,
  opacity: 0.8
})

let line = new LineSegments(planeGeometry, lineMaterial)
let plane = new Mesh(planeGeometry, planeMaterial)

group.add(plane)
group.add(line)

scene.add(group)

const controls = {
  width: planeGeometry.parameters.width,
  height: planeGeometry.parameters.height,
  color: planeMaterial.color.getStyle(),
  redraw() {
    // 移除旧数据
    group.remove(plane)
    group.remove(line)
    // 销毁
    planeGeometry.dispose()
    // 生成新几何体
    let newGeometry = new PlaneBufferGeometry(this.width, this.height, 1, 1)
  
    line = new LineSegments(newGeometry, lineMaterial)
    plane = new Mesh(newGeometry, planeMaterial)
  
    group.add(plane)
    group.add(line)
  }
}

const gui = new dat.GUI()
gui.addColor(controls, 'color').onChange(e => {
  planeMaterial.color.set(new Color(e))
})
gui.add(controls, 'width', 1, 40).onChange(e => controls.redraw())
gui.add(controls, 'height', 1, 40).onChange(e => controls.redraw())

const renderer = new WebGLRenderer({ antialias: true })
renderer.setPixelRatio(window.devicePixelRatio)
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.setClearColor(0x000000)

document.body.appendChild(renderer.domElement)

function render() {
  stats.update()

  group.rotation.y += 0.01

  requestAnimationFrame(render)
  renderer.render(scene, camera)
}

render()